<?php
class CueList
{
  private $cueFile;
  private $items = array();
  private $currentItem = array();
  private $nextItem = array();
  private $loopItems = true;
  
  public function __construct()
  {
    $this->cueFile = $_SESSION['MczSession']->getHomeDir().'/cue.list';
    if(is_file($this->cueFile))
    {
      $values = unserialize(file_get_contents($this->cueFile));
      
      $this->items        = $values['items'];
      $this->currentItem  = $values['currentItem'];
      $this->nextItem     = $values['nextItem'];
      $this->loopItems    = $values['loopItems'];
    }

    if(!empty($this->items))
    {
      reset($this->items);
      $this->nextItem = current($this->items);
    }

  }
  /**
   *A compléter
   */     
  public function scrobbleItem($itemId)
  {
    if($this->items[$itemId]['type'] != 'mczid')
    {
      return false;
      //return ('not part of library');
    }
    
    $lastfm_usr   = $_SESSION['MczSession']->getLastfmUsr();
    //echo 'usr:'.$lastfm_usr;
    $lastfm_pass  = $_SESSION['MczSession']->getLastfmPass();
    //echo 'pass:'.$lastfm_pass;
    
    if(empty($lastfm_usr) or empty($lastfm_pass))
    {
      return false;
      //return ('queud!');
    }
    $scrobbler = new Scrobbler($lastfm_usr,$lastfm_pass);
    if($scrobbler)
    {
      $song = new Song($this->items[$itemId]['res_id']);
      $values = $song->getAsArray();
      //print_r($values);
      $scrobbler->queue_track(utf8_encode(html_entity_decode($values['artist'],ENT_QUOTES)),utf8_encode(html_entity_decode($values['album'],ENT_QUOTES)),utf8_encode(html_entity_decode($values['title'],ENT_QUOTES)),time(),round($values['playtime']));
      $scrobbler->submit_tracks();
      $err_msg = $scrobbler->get_error_msg();
      if(empty($err_msg))
      {
        return true;
        //return ('scrobble yeah!');
      }
      
    }
    return false;
    //return ('scrobble failed!');
  }
  
  public function getItems()
  {
    return($this->items);
  }
  
  private function setNextItem()
  {
    $this->currentItem = $this->nextItem;
    reset($this->items);
    while($item = current($this->items))
    {
      if($item['id'] == $this->nextItem['id'])
      {
        if($this->nextItem = next($this->items))
        {
          return;
        }
        else
        {
          $this->nextItem = array();
          return;
        }
      }
      else
      {
        next($this->items);
      }
    }
  }
  
  private function fetchItemDatas()
  {
    if(!$_SESSION['MczSession']->can('play'))
    {
      return array('id'=>'','label'=>'','url'=>'');
    }
    $id   = $this->nextItem['id'];
    switch($this->nextItem['type'])
    {
      case 'mczid'://todo
        $type   = 'mcz';
        $song   = new Song($this->nextItem['res_id']);
        $label  = $song->getLabel();
        $url    = '?c=stream&id='.$this->nextItem['res_id'];
        $path   = SND_PATH.$song->getPath();
        break;
      case 'url':
        $type = 'url';
        $label= $this->nextItem['label'];
        $url  = urldecode($this->nextItem['res_id']);
        $path   = '';
        break;
    }
    return(array('id'=>$id,'label'=>$label,'url'=>$url,'uid'=>uniqid(),'type'=>$type,'path'=>$path));
  }
  
  public function getNextItem()
  {
    if($this->loopItems and empty($this->nextItem))
    {
      reset($this->items);
      $this->nextItem = current($this->items);
    }
    $datas = $this->fetchItemDatas();
    if($datas['type']=='mcz')
    {
			if(!is_readable($datas['path']))
			{
			  return(json_encode('file unavailable'));
			}
		}
    $this->setNextItem();
    return(json_encode($datas));
  }
  
  public function getItemById($id)
  {
    $this->nextItem = $this->items[$id];
    $datas = $this->fetchItemDatas();
    if($datas['type']=='mcz')
    {
			if(!is_readable($datas['path']))
			{
			  return(json_encode('file unavailable'));
			}
		}
    $this->setNextItem();
    return(json_encode($datas));
  }

  
  /**
   * Add an item to the cue and returns it's unique identifier
   * 
   * @param string $type url or mczid
   * @param string $label
   * @param string $res_id either a url (http//...) or a song id.   
   * 
   * @return string $id               
   */    
  public function addItem($type,$label,$res_id)
  {
    $id = uniqid('cue');
    if($type == 'mczid')
    {
      $song   = new Song($res_id);
      $label  = $song->getLabel();
    }
    if(empty($this->nextItem))
    {
      $this->nextItem = array('id'=>$id,'type'=>$type,'label'=>$label,'res_id'=>$res_id);
    }
    $this->items[$id] = array('id'=>$id,'type'=>$type,'label'=>$label,'res_id'=>$res_id);
    return(json_encode(array('id'=>$id,'item'=>$this->mkCueItem($id,$label))));
  }
  
  public function removeItem($id)
  {
    if(empty($this->nextItem['id']))
    {
      $this->nextItem['id'] = '';
    }
    if($id == $this->nextItem['id'])
    {
      $this->setNextItem();
    }
    unset($this->items[$id]);
    $this->items = array_merge($this->items);
    if(empty($this->items))
    {
      $this->nextItem = array();
    }
    return(json_encode(array('response'=>'ok','id'=>$id)));
  }
  
  public function updateOrder($hash)
  {
    $this->cueOrder = array();
    $items = explode('&',$hash);
    foreach($items as $item)
    {
      $xplode = explode('=',$item);
      $tab[$xplode[1]] = $this->items[$xplode[1]];
    }
    
    $this->items = $tab;
    
    while($item = current($this->items))// next item gets extra treatment here
    {
      if($item['id'] == $this->currentItem['id'])//currentItem instead of nextItem (see setNextItem())
      {
        if($this->nextItem = next($this->items))
        {
          return;
        }
        else
        {
          $this->nextItem = array();
          return;
        }
      }
      else
      {
        next($this->items);
      }
    }
    return(json_encode(array('response'=>'ok')));
  }
  
  private function toFile()
  {
    $values['items']        = $this->items;
    $values['currentItem']  = $this->currentItem;
    $values['nextItem']     = $this->nextItem;
    $values['loopItems']    = $this->loopItems;
    if(file_put_contents($this->cueFile,serialize($values)))
    {
      chmod($this->cueFile,0777);
      return true;
    }
    else
    {
      return false;
    }
  }
  
 
  private function mkCueItem($itemId,$itemLabel)
  {
    if(!isset($this->currentItem['id']))
    {
      $currClass = '';
    }
    else
    {
      if($itemId == $this->currentItem['id'])
      {
        $currClass = ' playinItem';
      }
      else
      {
        $currClass = '';
      }
    }
    $html = '<li id="'.$itemId.'" class="sortableItem"><span class="handle" onmouseover="help(str.hlp_handle);">&nbsp;</span><span class="itemControls"><input type="image" src="app/skin/transparent.gif" onclick="removeFromCue(\''.$itemId.'\');return false;" class="btnRemove" onmouseover="help(str.hlp_remove);"/></span><span class="lblCue'.$currClass.'" onmouseover="help(str.hlp_click_to_play);" onclick="play(\''.$itemId.'\');">'.$itemLabel.'</span></li>';
    return $html;
  }
  
  public function mkHtml()
  {
    $html = '<ul id="cueList">';
    foreach($this->items as $item)
    {
      $html.= $this->mkCueItem($item['id'],$item['label']);
    }
    $html.= '</ul>';
    return($html);
  }
  
  public function __destruct()
  {
    $this->toFile();
  }
}
?>
